from django.views import View
from django.http import JsonResponse, HttpResponse
import json
from rest_framework.viewsets import ModelViewSet

from booktest.models import BookInfo, HeroInfo
from booktest.serializers import BookInfoSerializer, HeroInfoSerializer
from .serializers import BookInfoModelSerializer


"""
GET     /books/         提供所有记录
POST    /books/         新增一条记录
GET     /books/<pk>/    提供指定id的记录
PUT     /books/<pk>/    修改指定id的记录
DELETE  /books/<pk>/    删除指定id的记录

响应数据    JSON
"""


class BookListView(View):
    """列表视图"""

    def get(self, request):
        """查询所有图书"""
        # 1.查询出所有图书模型对象
        books = BookInfo.objects.all()
        # 2.把模型转换成JSON字典
        # 定义一个列表变量
        book_list = []
        for book in books:
            book_dict = {
                'id': book.id,
                'btitle': book.btitle,
                'bpub_date': book.bpub_date,
                'bread': book.bread,
                'bcomment': book.bcomment,
                'image': book.image.url if book.image else ''
            }
            book_list.append(book_dict)
        # 3.响应

        return JsonResponse(book_list, safe=False)


    def post(self, request):
        """新增一本图书"""
        # 1.获取请求中的JSON数据
        json_bytes = request.body
        json_str = json_bytes.decode()
        # 2.把bytes类型的数据转换成json字典
        json_dict = json.loads(json_str)

        # 前端传入的数据不能直接使用,都必须经过校验

        # 3.创建模型对象,赋值并存储到数据库
        book = BookInfo.objects.create(
            btitle=json_dict.get('btitle'),
            bpub_date=json_dict.get('bpub_date')
        )
        # 3.1 把新增的模型对象转换成json字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
        # 4.响应
        return JsonResponse(book_dict, status=201)


class BookDetailView(View):
    """详情视图"""

    def get(self, request, pk):
        """查询单一"""
        # 1.查询出pk所指定的那个数据
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 2.把模型对象转换成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
        # 3.响应
        return JsonResponse(book_dict)


    def put(self, request, pk):
        """修改单一"""
        # 0.获取前端传入的数据(校验)
        json_bytes = request.body
        json_str = json_bytes.decode()
        json_dict = json.loads(json_str)
        # json.loads(request.body.decode())
        # 1.获取出要修改的那模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 2.修改模型属性值
        book.btitle = json_dict.get('btitle')
        # 3.save()
        book.save()
        # 4.把修改后的模型对象转换成字典
        book_dict = {
            'id': book.id,
            'btitle': book.btitle,
            'bpub_date': book.bpub_date,
            'bread': book.bread,
            'bcomment': book.bcomment,
            'image': book.image.url if book.image else ''
        }
        # 响应
        return JsonResponse(book_dict)

    def delete(self, request, pk):
        """删除单一"""
        # 根据pk获取出要删除的模型对象
        try:
            book = BookInfo.objects.get(id=pk)
        except BookInfo.DoesNotExist:
            return HttpResponse(status=404)
        # 删除delete
        book.delete()
        # 响应
        return HttpResponse(status=204)


class BookInfoViewSet(ModelViewSet):
    """定义视图集"""
    # 指定序列化器
    serializer_class = BookInfoModelSerializer
    # 指定查询
    queryset = BookInfo.objects.all()


# book = BookInfo.objects.get(id=1)
# # 创建序列化器进行序列化器
# # 给instance参数传入实参  可以传模型/查询集(many=True)/字典
# serializer = BookInfoSerializer(instance=book)
# # serializer = BookInfoSerializer(book)
# serializer.data

# 序列化查询集
# books = BookInfo.objects.all()
# serializer = BookInfoSerializer(books, many=True)
# # serializer = BookInfoSerializer({'books': books})
# serializer.data


# 关联序列化
# hero = HeroInfo.objects.get(id=1)
# serializer = HeroInfoSerializer(hero)
# serializer.data



"""以下代码是进行反序列操作演练"""
from booktest.serializers import BookInfoSerializer
data = {
    'btitle': '三国django',
    'bpub_date': '1991-11-11',
    'bread': 25,
    'bcomment': 22
}
serializer = BookInfoSerializer(data=data)
if serializer.is_valid(raise_exception=True):
    serializer.save()  # 将校验后的数据修改到数据库
    # 当序列化器调用save方法 会去执行序列化器中的create方法或update方法





